// import ol from 'ol' 
//地图渲染 及地图初始化方法
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
import Map from 'ol/Map'
import {defaults} from 'ol/interaction'
import Select from 'ol/interaction/Select'
import View from 'ol/View'
import {transform, transformExtent, fromLonLat, toLonLat} from 'ol/proj'
import MousePosition from 'ol/control/MousePosition'
import {format} from 'ol/coordinate'
import WKT from 'ol/format/WKT'
import WebGLPointsLayer from 'ol/layer/WebGLPoints'
import VectorSource from 'ol/source/Vector'
import VectorLayer from 'ol/layer/Vector'
import Feature from 'ol/Feature'
import Point from 'ol/geom/Point'
import Style from 'ol/style/Style'
import Stroke from 'ol/style/Stroke'
import CircleStyle from 'ol/style/Circle'
import FeatureStyle from '@/assets/dist/FeatureStyle'
import Fill from 'ol/style/Fill'
import Overlay from 'ol/Overlay';
import store from "../../store";
import ImageLayer from "ol/layer/Image"
import ImageStatic from "ol/source/ImageStatic"
//变量
let MyMap=undefined
let _this = this
let content = undefined
let selectSingleClick={}
let wktLayers = {}
let vetorList = []
var overlay =undefined
let selectSingles={};
let mapURL = 'http://t{1-7}.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=df5b7775fab31595f6c43caadb9af47d|http://t{1-7}.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=df5b7775fab31595f6c43caadb9af47d'
// 底图 图层变量
let baseMapLayer = {
	tileLayer: new TileLayer({
	source: new XYZ({
    url: mapURL.split('|')[0]
    })
  }),

	labelLayer: new TileLayer({
    zIndex: 1,
	source: new XYZ({
    url: mapURL.split('|')[1]
    })
  })
}

//创建地图方法
//type： 

export function createMap() {	
    MyMap = new Map({
        target: 'map',
        logo: false,
        layers: null,
        interactions: defaults({
            doubleClickZoom: false
        }),
        view: new View({
            projection: "EPSG:4326",
            center: [113.94261734587297, 22.57669954443905],
            zoom: 15,
            minZoom: 6,  
            maxZoom: 18.5
        }),
    })
    let temp = null
    const mousePositionControl = new MousePosition({
        coordinateFormat: function (coordinate) {
        temp = coordinate
            return format(coordinate, '经度:{x}°E 纬度:{y}°N', 2)
        },
        projection: 'EPSG:4326',
        className: 'ol-mouse-position',
        target: document.getElementById('mouse-position'),
    })
    MyMap.addControl(mousePositionControl)// 实例化坐标拾取控件，并加入地
    MyMap.addLayer(baseMapLayer.tileLayer) //矢量图
    MyMap.addLayer(baseMapLayer.labelLayer) //影像图
	
	// 监听地图缩放，
	MyMap.on('moveend', function(e) {
		// console.log('当前地图层级', map.getView().getZoom())
	})
	MyMap.on('pointermove',function(e){
		var pixel = MyMap.getEventPixel(e.originalEvent);
		var hit = MyMap.hasFeatureAtPixel(pixel);
		if(hit){
			MyMap.getTargetElement().style.cursor = 'pointer';
		}
		else{
			MyMap.getTargetElement().style.cursor = '';
		}
   	});//add by huanghong 鼠标悬浮在专题图上变手指
	// 监听地图单击
	// map.on('singleclick', evt => {
	// 	console.log(evt.coordinate)
	// })
	//气泡
	//弹出气泡
	var container = document.getElementById('popup');
	content = document.getElementById('popup-content');

	overlay = new Overlay({
	element: container,
	autoPan: true,
	autoPanAnimation: {
		duration: 250,
	},
	});
	MyMap.addOverlay(overlay);

	var closer = document.getElementById('popup-closer');
	// closer.onclick = function () {
	// 	overlay.setPosition(undefined);
	// 	closer.blur();
	// 	return false;
	// };

	// return MyMap
}
// 设置底图 地图切换
export function setBaseMap (layer) {
	MyMap.removeLayer(baseMapLayer.tileLayer)
	MyMap.removeLayer(baseMapLayer.labelLayer)

  let source = null
  let type = layer.typeName
  let url = layer.url
  let labelSource = baseMapLayer.labelLayer.getSource()
  if (labelSource) {
	baseMapLayer.labelLayer.setSource(null)
  }
  if (type === 'tianditu' || type === 'xyz') {
	source = new XYZ({
	  // crossOrigin: 'anonymous',
	  url: url.split('|')[0]
	})
	let labelSource = new XYZ({
	  // crossOrigin: 'anonymous',
	  url: url.split('|')[1]
	})
	baseMapLayer.labelLayer.setZIndex(-1)
	baseMapLayer.labelLayer.setSource(labelSource)
  }
  baseMapLayer.tileLayer.setSource(source)
	baseMapLayer.tileLayer.setZIndex(-2)
	MyMap.addLayer(baseMapLayer.tileLayer)
	MyMap.addLayer(baseMapLayer.labelLayer)
	MyMap.index = -1
}

//数据类型判断
function getGeoType(geo){
    if(geo.indexOf("POLYGON")!=-1){
        return "POLYGON"
    }
    else if(geo.indexOf("LINESTRING")!=-1){
        return "LINESTRING"
    }
    else if(geo.indexOf("minLine")!=-1){
        return "minLine"
    }
    else if(geo.indexOf("POINT")!=-1){
        return "POINT"
    }
    else if(geo.indexOf("ICON")!=-1){
        return "ICON"
    }
    else if(geo.indexOf("oldICON")!=-1){
        return "oldICON"
    }
    else{
        return ""
    }
}

/**计算中心点坐标 */
function getCoordinate(feature,evt){
	let coordinate = [];
	if(feature!=undefined){
		let geometry = feature.getGeometry();
		if (geometry instanceof Point) {  //拿到点的坐标
			coordinate = geometry.getCoordinates();
		} else{
			coordinate = geometry.getInteriorPoint?geometry.getInteriorPoint().getCoordinates():evt.mapBrowserEvent.coordinate;
		}
	}
	return coordinate
}
//生成唯一图层id
function randomString() {  
    e = 32;
    var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
    a = t.length,
    n = "";
    for (i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
    let timestamp = Date.parse(new Date());
    return n+timestamp
  }

//图层点击事件
function  poiClick(evt){
	let feature = evt.selected[0];
	if(feature!=undefined){
		let coordinate = getCoordinate(feature,evt);
		let propertiesVal = feature.properties;
		store.dispatch('changClickMap', propertiesVal);
		// console.log(store.getters.popupData)
		overlay.setPosition(coordinate);
	}
	else{
		MyMap.selectSingleClick.getFeatures().clear()
		overlay.setPosition(undefined);
	}
}

//绘制图形
export function drawWKT(geomstring) {
	let wkt = geomstring.the_geom
	let format = new WKT(wkt)
	let feature = format.readFeature(wkt)
	feature.properties=geomstring
	const geoType = getGeoType(wkt); //判断数据点线面
	let mycolor = geomstring.showColor
	// removeWKT (geomstring)
	let vectorWKT = new VectorLayer({
			source: new VectorSource({
				features: [feature]
			}),
			opacity: 0.4,
			style:FeatureStyle.getStyle(geoType,mycolor)
	})
	MyMap.removeInteraction(selectSingleClick);//移除之前的图层
	vetorList.push(vectorWKT)
	selectSingleClick = new Select({
		layers: vetorList,
		style: new Style({
			image: new CircleStyle({
				radius: 5,
				fill: new Fill({
					color: '#09f'
				}),
				stroke: new Stroke({
					color:'#fff',
					width: 4
				})
			}),
			stroke: new Stroke({
				color: '#ED1C24',
				width: 3
			}),
			fill: new Fill({
				color: 'rgba(114,111,228,0.8)'
			})
		}),
		hitTolerance:0
	});
	// selectSingles[geomstring.ID+geomstring.name] = selectSingleClick;
	MyMap.addInteraction(selectSingleClick);
	MyMap.selectSingleClick = selectSingleClick;
	selectSingleClick.on('select', poiClick); //图层点击
	wktLayers[geomstring.ID+geomstring.name] = vectorWKT

	MyMap.addLayer(vectorWKT);
}

//移除绘制图层
export function removeWKT (geomstring) {
	let wkt = geomstring.ID+geomstring.name
	if(wktLayers[wkt]!=undefined) {
		let index = vetorList.indexOf(wktLayers[wkt])
		index>-1&&vetorList.splice(index, 1);
		MyMap.removeLayer(wktLayers[wkt])
		overlay.setPosition(undefined);
		delete wktLayers[wkt]
	}
}
function clearWKT () {
	Object.keys(wktLayers).forEach(key => {
		MyMap.removeLayer(wktLayers[key])
	  delete wktLayers[key]
	})
}

//地图平缓飞行动画
function flyTo(location) {
	var duration = 2000;
	let view = MyMap.getView();
	var zoom = view.getZoom();
	var parts = 2;
	var called = false;
	function callback(complete) {
	  --parts;
	  if (called) {
		return;
	  }
	  if (parts === 0 || !complete) {
		called = true;
	  }
	}
	view.animate(
	  {
		center: location,
		duration: duration,
	  },
	  callback
	);
	view.animate(
	  {
		zoom: zoom - 1,
		duration: duration / 2,
	  },
	  {
		zoom: zoom,
		duration: duration / 2,
	  },
	  callback
	);
  }

//列表要素点击事件
export function flyToFeature(dataFeature){
	let wkt = dataFeature.ID+dataFeature.name;
	if(wktLayers[wkt]!=undefined){
		let selectLayer = wktLayers[wkt];
		let feature =selectLayer.getSource().getFeatures()[0]; 
		let coordinate = getCoordinate(feature);
		overlay.setPosition(undefined);
		MyMap.selectSingleClick.getFeatures().clear()//先清空
		MyMap.selectSingleClick.getFeatures().push(selectLayer);
		MyMap.getView().setZoom(18);
		flyTo(coordinate)
	}
}